# author zybz 2022.3.16
import cv2
import os


class video_and_photo():
    def get_video_from_webcam(self, video_name='default', video_save_path='Video', img_w=640, img_h=480):
        """get video from webcam

        Args:
            video_name (str): the video name you wish to save
            video_save_path (str, optional): the video path you wish to save. Defaults to 'Video'.
            img_w (int, optional): video width. Defaults to 640.
            img_h (int, optional): video height. Defaults to 480.
        """
        print("-----you choose to get video from webcam-----")
        camera = cv2.VideoCapture(0)
        assert camera.isOpened(), 'Failed to open camera'
        camera.set(cv2.CAP_PROP_FRAME_WIDTH, img_w)
        camera.set(cv2.CAP_PROP_FRAME_HEIGHT, img_h)
        print("capture device is open: " + str(camera.isOpened()))

        width = camera.get(cv2.CAP_PROP_FRAME_WIDTH)  # 获取摄像头width
        height = camera.get(cv2.CAP_PROP_FRAME_HEIGHT)  # 获取摄像头height
        size = (int(width), int(height))

        fourcc = cv2.VideoWriter_fourcc(*'DIVX')  # 定义编解码器并创建VideoWriter对象
        # 参数还可以 DIVX，XVID，MJPG，X264，WMV1，WMV2。
        vpath = video_save_path

        if not (os.path.exists(vpath)):
            # print('n')  #没有就建一个
            os.makedirs(vpath)
        # 创建VideoWriter，用于写视频
        out = cv2.VideoWriter(vpath + '\\' + video_name + '.mp4', fourcc, 24.0, size)

        while True:
            ret, img = camera.read()
            if ret is False:
                break
            out.write(img)
            cv2.imshow("img", img)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                cv2.destroyAllWindows()
                break
        camera.release()

        cv2.destroyAllWindows()
        out.release()
        print("get video from webcam successfully")

    def get_pictures_from_video(self, video_path, save_path='images1', time_frequency=20):
        """get pictures from video

        Args:
            video_path (str): the video you want to get pictures from
            save_path (str, optional): the pictures where to save. Defaults to 'images1'.
            time_frequency (int, optional): _description_. Defaults to 20.
        """
        print("-----you choose to get pictures from video-----")
        vc = cv2.VideoCapture(video_path)  # 读入视频文件，命名cv
        n = 1  # 计数

        if vc.isOpened():  # 判断是否正常打开
            rval, frame = vc.read()
        else:
            rval = False

        time_frequency = 20  # 视频帧计数间隔频率
        if not (os.path.exists(save_path)):
            os.makedirs(save_path)

        i = 0
        while rval:  # 循环读取视频帧
            rval, frame = vc.read()
            if (n % time_frequency == 0):  # 每隔timeF帧进行存储操作
                i += 1
                print(i)
                cv2.imwrite(save_path + '/{}'.format(str(i).zfill(4) + '.jpg'), frame)  # 存储为图像
            n = n + 1
            cv2.waitKey(1)
        vc.release()
        print("get pictures from video successfully")


if __name__ == '__main__':
    demo = video_and_photo()
    # demo.get_video_from_webcam()
    # demo.get_pictures_from_video(video_path='Video/default.mp4')
